package com.ynny.jdbc01;

import com.mysql.cj.jdbc.Driver;

import java.sql.*;

public class JDBCDemo03 {

    public static void main(String[] args) throws SQLException {
        Driver driver = new Driver();
        DriverManager.registerDriver(driver);
        String url = "jdbc:mysql://localhost:3306/db01";
        String userName = "root";
        String password ="root";
        Connection connection = DriverManager.getConnection(url, userName, password);

        //4.得到PreparedStatement
        // 4.1携带参数
        //    ?  占位符

        String sql = "select * from book where name = ? and id = ?";

        PreparedStatement preparedStatement =
                connection.prepareStatement(sql);

        //  4.2给占位符赋值
        //     parameterIndex 参数的下标 ----> 从1开始
             preparedStatement.setString(1,"喜羊羊");
             preparedStatement.setString(2,"7");
        //5.执行sql语句
        ResultSet resultSet = preparedStatement.executeQuery();

        //6.解析结果集

        //判断结果集里面是否有下一条数据
        while (resultSet.next()) {

            String id = resultSet.getString("id");
            String name = resultSet.getString("name");

            System.out.println(id + "\t" + name);

        }

        //7.关闭连接
        resultSet.close();
        preparedStatement.close();
        connection.close();


    }
}
